/*
 * 
 * 
 * 
 */
package com.cms.template.directive;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cms.entity.Content;
import com.cms.entity.Site;
import com.cms.service.ContentService;
import com.cms.utils.FreeMarkerUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 模板指令 - 内容分页
 * 
 * 
 * 
 */
@Component
public class ContentPageDirective extends BaseDirective {

	@Autowired
	private ContentService contentService;

	/** "栏目ID"参数名称 */
	private static final String CATEGORY_ID_PARAMETER_NAME = "categoryId";

	/** "栏目编码"参数名称 */
	private static final String CATEGORY_CODE_PARAMETER_NAME = "categoryCode";

	/** "标签ID"参数名称 */
	private static final String TAG_ID_PARAMETER_NAME = "tagId";
	
    /** "搜索词"参数名称 */
    private static final String KEYWORD_PARAMETER_NAME = "keyword";
    
    /** "页码"参数名称 */
    private static final String PAGE_NUMBER_PARAMETER_NAME = "pageNumber";
    
    /** "每页记录数"参数名称 */
    private static final String PAGE_SIZE_PARAMETER_NAME = "pageSize";

	/** 变量名称 */
	private static final String VARIABLE_NAME = "contentPage";

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	    Site currentSite = getCurrentSite();
	    Integer siteId = currentSite.getId();
		Integer categoryId = FreeMarkerUtils.getParameter(CATEGORY_ID_PARAMETER_NAME, Integer.class, params);
        String categoryCode = FreeMarkerUtils.getParameter(CATEGORY_CODE_PARAMETER_NAME, String.class, params);
		Integer tagId = FreeMarkerUtils.getParameter(TAG_ID_PARAMETER_NAME, Integer.class, params);
		String keyword = FreeMarkerUtils.getParameter(KEYWORD_PARAMETER_NAME, String.class, params);
		Integer pageNumber = FreeMarkerUtils.getParameter(PAGE_NUMBER_PARAMETER_NAME, Integer.class, params);
		Integer pageSize = FreeMarkerUtils.getParameter(PAGE_SIZE_PARAMETER_NAME, Integer.class, params);
		String condition = getCondition(params);
		String orderBy = getOrderBy(params);
		Page<Content> page = contentService.findPage(categoryId,categoryCode,tagId,keyword,condition, orderBy,pageNumber,pageSize,siteId);
		TemplateModel preVariable = FreeMarkerUtils.getVariable(VARIABLE_NAME, env);
		try {
			FreeMarkerUtils.setVariable(VARIABLE_NAME, page, env);
			env.getOut().write("<!--totalPageStart("+page.getPages()+")totalPageEnd-->");
			body.render(env.getOut());
		} finally {
			FreeMarkerUtils.setVariable(VARIABLE_NAME, preVariable, env);
		}
	}
}